import React, { useEffect, useState } from 'react';
// @ts-ignore
import Vditor from 'vditor/dist/method.min';
import 'vditor/src/assets/scss/index.scss';
import styles from './index.less';

//@ts-ignore
const initOutline = () => {
  const headingElements: Element[] = [];
  const preview = document.getElementById('preview');
  if (!preview) {
    return;
  }
  Array.from(preview.children).forEach((item) => {
    if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
      headingElements.push(item);
    }
  });

  let toc: { id: string, offsetTop: number }[] = [];
  return window.addEventListener('scroll', () => {
    const scrollTop = window.scrollY;
    toc = [];
    headingElements.forEach((item) => {

      toc.push({
        id: item.id,
        // @ts-ignore
        offsetTop: item.offsetTop,
      });
    });

    const currentElement = document.querySelector('.vditor-outline__item--current');
    for (let i = 0, iMax = toc.length; i < iMax; i++) {
      if (scrollTop < toc[i].offsetTop - 30) {
        if (currentElement) {
          currentElement.classList.remove('vditor-outline__item--current');
        }
        let index = i > 0 ? i - 1 : 0;
        const spIndex = document.querySelector('span[data-target-id="' + toc[index].id + '"]');
        if (spIndex) {
          spIndex.classList.add('vditor-outline__item--current');
        }
        break;
      }
    }
  });
};

export type VditorPreviewType = {
  markdown: string;
};

const VditorPreview: React.FC<VditorPreviewType> = ({ markdown }) => {

  const [html, setHtml] = useState<string>('');

  //html渲染后初始化md
  useEffect(() => {
    // @ts-ignore
    Vditor.md2html(markdown,
      {
        mode: 'light',
        hljs: {
          enable: true,
          style: 'native',
          lineNumber: true,
        },
        markdown:{
          codeBlockPreview: true,
        },
        speech: {
          enable: true,
        },
        anchor: 1,
      },
    ).then((value: string) => {
      setHtml(value);
    });

  }, [markdown]);

  useEffect(() => {
    let scrollEvent: any;
    if (window.innerWidth <= 768) {
      return;
    }
    const outlineElement = document.getElementById('outline');
    // @ts-ignore
    Vditor.outlineRender(document.getElementById('preview'), outlineElement);

    if (outlineElement && outlineElement.innerText.trim() !== '') {
      outlineElement.style.display = 'block';
      scrollEvent = initOutline();
    }
    return () => {
      if (scrollEvent) {
        window.removeEventListener('scroll', scrollEvent);
      }
    };
  }, [html]);

  return <div className={styles.inlineStyles}>
    <div id={'preview'} dangerouslySetInnerHTML={{ __html: html }} />
    <div id={'outline'} />
    <div style={{ display: 'none' }}>{markdown}</div>
  </div>;
};

export default VditorPreview;
